import React, { useState, useEffect, useRef } from 'react'
import { Table, Button, Space, Select, Input, message, Modal, Form, Upload, Dropdown } from 'antd'
import { UploadOutlined, DownloadOutlined, DownOutlined } from '@ant-design/icons'
import axios from 'axios'
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'
import { Document, Packer, Paragraph, Table as DocxTable, TableRow, TableCell, WidthType, AlignmentType } from 'docx'
import jsPDF from 'jspdf'
import html2canvas from 'html2canvas'

/**
 * 员工绩效管理页面
 * 
 * 功能说明：
 * 1. 导出功能：将当前表格数据导出为Excel文件
 * 2. 导入功能：通过Excel文件批量导入员工绩效数据
 * 3. 下载模板：下载Excel模板文件，了解正确的导入格式
 * 
 * Excel导入格式要求：
 * - 必需字段：姓名、部门、职位、角色、工时成本
 * - 可选字段：手机号
 * - 文件格式：.xlsx 或 .xls
 * - 文件大小：不超过5MB
 */

export default function EmployeePerformance() {
  const [dataSource, setDataSource] = useState([])
  const [originalData, setOriginalData] = useState([]) // 保存原始数据
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [form] = Form.useForm()
  const [departmentOptions, setDepartmentOptions] = useState([])
  const [roleOptions, setRoleOptions] = useState([])
  const [employeeOptions, setEmployeeOptions] = useState([])
  const [positionOptions, setPositionOptions] = useState([])
  // 搜索条件状态
  const [searchName, setSearchName] = useState('')
  const [searchRole, setSearchRole] = useState('')
  const fileInputRef = useRef(null)

  // 编辑功能相关状态
  const [isEditModalOpen, setIsEditModalOpen] = useState(false) // 编辑模态框显示状态
  const [currentEditData, setCurrentEditData] = useState(null) // 当前编辑的数据
  const [editForm] = Form.useForm() // 编辑表单实例

  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '部门',
      dataIndex: 'department',
      key: 'department'
    },
    {
      title: '职位',
      dataIndex: 'position',
      key: 'position'
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role'
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone'
    },
    {
      title: '公时成本',
      dataIndex: 'workcost',
      key: 'workcost'
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            size="small"
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
        </Space>
      )
    }
  ]

  const [pageSize, setPageSize] = useState(10)
  const getList = async () => {
    let res = await axios.get('http://localhost:3000/EmployeePerformance/list')
    if (res.data.code === 200) {
      const newData = res.data.data.map((item, index) => {
        return {
          ...item,
          key: item._id
        }
      })
      setDataSource(newData)
      setOriginalData(newData) // 保存原始数据

      // Extract unique values for dropdowns
      const departments = [...new Set(newData.map(item => item.department))].map(dept => ({
        value: dept,
        label: dept
      }))
      // console.log(departments,73);

      const roles = [...new Set(newData.map(item => item.role))].map(role => ({
        value: role,
        label: role
      }))

      const employees = [...new Set(newData.map(item => item.name))].map(name => ({
        value: name,
        label: name
      }))
      const positions = [...new Set(newData.map(item => item.position))].map(position => ({
        value: position,
        label: position
      }))
      // console.log(positions, 89);
      setPositionOptions(positions)
      setDepartmentOptions(departments)
      setRoleOptions(roles)
      setEmployeeOptions(employees)
    }
  }

  useEffect(() => {
    getList()
  }, [])

  const handleDelete = async () => {
    let res = await axios.post('http://localhost:3000/EmployeePerformance/deleteAll', {
      ids: selectedRowKeys
    })
    if (res.data.code === 200) {
      message.success('删除成功')
      getList()
    }
    setSelectedRowKeys([])
  }

  // 表格选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys) => {
      setSelectedRowKeys(newSelectedRowKeys)
    },
    selections: [
      {
        key: 'all-data',
        text: '全选所有',
        onSelect: () => {
          setSelectedRowKeys(dataSource.map(item => item.key))
        },
      },
      {
        key: 'clear',
        text: '取消选择',
        onSelect: () => {
          setSelectedRowKeys([])
        },
      },
    ],
  }

  // 模态框表单提交
  const handleOk = () => {
    form.validateFields().then(values => {
      // TODO: 提交表单数据到后端
      axios.post('http://localhost:3000/EmployeePerformance/add', values).then(res => {
        if (res.data.code === 200) {
          message.success('添加成功')
          getList()
          setIsModalOpen(false)
          form.resetFields()
        }
      })
    })
  }
  const handleCancel = () => {
    setIsModalOpen(false)
    form.resetFields()
  }

  // 查询功能
  const handleSearch = () => {
    let filteredData = [...originalData]

    // 按姓名搜索
    if (searchName.trim()) {
      filteredData = filteredData.filter(item =>
        item.name && item.name.toLowerCase().includes(searchName.toLowerCase())
      )
    }

    // 按角色搜索
    if (searchRole) {
      filteredData = filteredData.filter(item =>
        item.role === searchRole
      )
    }

    setDataSource(filteredData)
  }

  // 重置功能
  const handleReset = () => {
    setSearchName('')
    setSearchRole('')
    setDataSource([...originalData])
  }

  // 导出功能 - 修改为支持多种格式
  const handleExport = async (format) => {
    try {
      // 1. 整理需要导出的数据，只保留需要的字段
      const exportData = dataSource.map(item => ({
        '姓名': item.name,
        '部门': item.department,
        '职位': item.position,
        '角色': item.role,
        '手机号': item.phone,
        '工时成本': item.workcost
      }))

      let fileName = ''
      let data = null

      switch (format) {
        case 'excel':
          // Excel导出逻辑
          const ws = XLSX.utils.json_to_sheet(exportData)
          const wb = XLSX.utils.book_new()
          XLSX.utils.book_append_sheet(wb, ws, '员工绩效数据')
          const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
          data = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
          fileName = `员工绩效数据_${new Date().toISOString().split('T')[0]}.xlsx`
          break

        case 'word':
          // Word导出逻辑
          try {
            // 创建表格行
            const tableRows = [
              // 表头行
              new TableRow({
                children: Object.keys(exportData[0]).map(header => 
                  new TableCell({
                    children: [new Paragraph({ text: header, alignment: AlignmentType.CENTER })],
                    width: { size: 2000, type: WidthType.DXA }
                  })
                )
              }),
              // 数据行
              ...exportData.map(row => 
                new TableRow({
                  children: Object.values(row).map(value => 
                    new TableCell({
                      children: [new Paragraph({ text: value?.toString() || '', alignment: AlignmentType.CENTER })],
                      width: { size: 2000, type: WidthType.DXA }
                    })
                  )
                })
              )
            ]

            // 创建文档
            const doc = new Document({
              sections: [{
                properties: {},
                children: [
                  new Paragraph({
                    text: '员工绩效数据报表',
                    heading: 'Heading1',
                    alignment: AlignmentType.CENTER
                  }),
                  new Paragraph({
                    text: `导出时间：${new Date().toLocaleString()}`,
                    alignment: AlignmentType.CENTER
                  }),
                  new Paragraph({ text: '' }), // 空行
                  new DocxTable({
                    width: { size: 100, type: WidthType.PERCENTAGE },
                    rows: tableRows
                  })
                ]
              }]
            })

            // 生成Word文档
            const blob = await Packer.toBlob(doc)
            data = blob
            fileName = `员工绩效数据_${new Date().toISOString().split('T')[0]}.docx`
          } catch (error) {
            console.error('Word导出失败:', error)
            message.error('Word格式导出失败')
            return
          }
          break

        case 'pdf':
          // PDF导出逻辑
          try {
            // 创建临时HTML元素用于生成PDF
            const tempDiv = document.createElement('div')
            tempDiv.style.position = 'absolute'
            tempDiv.style.left = '-9999px'
            tempDiv.style.top = '-9999px'
            tempDiv.style.width = '800px'
            tempDiv.style.padding = '20px'
            tempDiv.style.fontFamily = 'Arial, sans-serif'
            tempDiv.style.backgroundColor = 'white'
            
            tempDiv.innerHTML = `
              <div style="text-align: center; margin-bottom: 30px;">
                <h1 style="color: #333; margin-bottom: 10px;">员工绩效数据报表</h1>
                <p style="color: #666; font-size: 14px;">导出时间：${new Date().toLocaleString()}</p>
              </div>
              
              <div style="margin-bottom: 30px; display: flex; justify-content: space-around; text-align: center;">
                <div>
                  <div style="font-size: 24px; font-weight: bold; color: #1890ff;">${exportData.length}</div>
                  <div style="color: #666; font-size: 12px;">总员工数</div>
                </div>
                <div>
                  <div style="font-size: 24px; font-weight: bold; color: #1890ff;">${[...new Set(exportData.map(item => item['部门']))].length}</div>
                  <div style="color: #666; font-size: 12px;">部门数量</div>
                </div>
                <div>
                  <div style="font-size: 24px; font-weight: bold; color: #1890ff;">${[...new Set(exportData.map(item => item['角色']))].length}</div>
                  <div style="color: #666; font-size: 12px;">角色类型</div>
                </div>
              </div>
              
              <table style="width: 100%; border-collapse: collapse; font-size: 12px;">
                <thead>
                  <tr style="background-color: #f8f9fa;">
                    ${Object.keys(exportData[0]).map(header => 
                      `<th style="border: 1px solid #ddd; padding: 8px; text-align: center; font-weight: bold;">${header}</th>`
                    ).join('')}
                  </tr>
                </thead>
                <tbody>
                  ${exportData.map(row => `
                    <tr>
                      ${Object.values(row).map(value => 
                        `<td style="border: 1px solid #ddd; padding: 6px; text-align: center;">${value || ''}</td>`
                      ).join('')}
                    </tr>
                  `).join('')}
                </tbody>
              </table>
            `
            
            document.body.appendChild(tempDiv)
            
            // 使用html2canvas将HTML转换为canvas
            const canvas = await html2canvas(tempDiv, {
              scale: 2,
              useCORS: true,
              allowTaint: true,
              backgroundColor: '#ffffff'
            })
            
            // 移除临时元素
            document.body.removeChild(tempDiv)
            
            // 创建PDF
            const imgData = canvas.toDataURL('image/png')
            const pdf = new jsPDF('p', 'mm', 'a4')
            const imgWidth = 210
            const pageHeight = 295
            const imgHeight = (canvas.height * imgWidth) / canvas.width
            let heightLeft = imgHeight
            
            let position = 0
            
            pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight)
            heightLeft -= pageHeight
            
            while (heightLeft >= 0) {
              position = heightLeft - imgHeight
              pdf.addPage()
              pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight)
              heightLeft -= pageHeight
            }
            
            // 生成PDF文件
            const pdfBlob = pdf.output('blob')
            data = new Blob([pdfBlob], { type: 'application/pdf' })
            fileName = `员工绩效数据_${new Date().toISOString().split('T')[0]}.pdf`
          } catch (error) {
            console.error('PDF导出失败:', error)
            message.error('PDF格式导出失败')
            return
          }
          break

        case 'ppt':
          // PPT导出逻辑 - 生成HTML格式的演示文稿
          const pptContent = `
            <!DOCTYPE html>
            <html>
            <head>
              <meta charset="utf-8">
              <title>员工绩效数据演示文稿</title>
              <style>
                body { font-family: Arial, sans-serif; margin: 0; padding: 20px; background: #f0f0f0; }
                .slide { background: white; margin: 20px auto; padding: 40px; border-radius: 10px; box-shadow: 0 4px 8px rgba(0,0,0,0.1); max-width: 800px; }
                .title { text-align: center; color: #333; font-size: 28px; margin-bottom: 30px; }
                .subtitle { text-align: center; color: #666; font-size: 16px; margin-bottom: 40px; }
                table { width: 100%; border-collapse: collapse; margin-top: 20px; }
                th, td { border: 1px solid #ddd; padding: 12px; text-align: center; }
                th { background-color: #f8f9fa; font-weight: bold; }
                .stats { display: flex; justify-content: space-around; margin: 30px 0; }
                .stat-item { text-align: center; }
                .stat-number { font-size: 24px; font-weight: bold; color: #1890ff; }
                .stat-label { color: #666; margin-top: 5px; }
              </style>
            </head>
            <body>
              <div class="slide">
                <div class="title">员工绩效数据报表</div>
                <div class="subtitle">${new Date().toLocaleString()}</div>
                <div class="stats">
                  <div class="stat-item">
                    <div class="stat-number">${exportData.length}</div>
                    <div class="stat-label">总员工数</div>
                  </div>
                  <div class="stat-item">
                    <div class="stat-number">${[...new Set(exportData.map(item => item['部门']))].length}</div>
                    <div class="stat-label">部门数量</div>
                  </div>
                  <div class="stat-item">
                    <div class="stat-number">${[...new Set(exportData.map(item => item['角色']))].length}</div>
                    <div class="stat-label">角色类型</div>
                  </div>
                </div>
              </div>
              
              <div class="slide">
                <div class="title">员工绩效详细数据</div>
                <table>
                  <thead>
                    <tr>
                      ${Object.keys(exportData[0]).map(header => `<th>${header}</th>`).join('')}
                    </tr>
                  </thead>
                  <tbody>
                    ${exportData.map(row => `
                      <tr>
                        ${Object.values(row).map(value => `<td>${value || ''}</td>`).join('')}
                      </tr>
                    `).join('')}
                  </tbody>
                </table>
              </div>
            </body>
            </html>
          `
          data = new Blob([pptContent], { type: 'text/html' })
          fileName = `员工绩效数据_${new Date().toISOString().split('T')[0]}.html`
          break

        case 'csv':
          // CSV导出逻辑
          const csvContent = [
            Object.keys(exportData[0]).join(','),
            ...exportData.map(row => Object.values(row).join(','))
          ].join('\n')
          data = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
          fileName = `员工绩效数据_${new Date().toISOString().split('T')[0]}.csv`
          break

        case 'txt':
          // TXT导出逻辑
          const txtContent = exportData.map(row => 
            Object.entries(row).map(([key, value]) => `${key}: ${value}`).join(' | ')
          ).join('\n')
          data = new Blob([txtContent], { type: 'text/plain;charset=utf-8' })
          fileName = `员工绩效数据_${new Date().toISOString().split('T')[0]}.txt`
          break

        case 'json':
          // JSON导出逻辑
          const jsonContent = JSON.stringify(exportData, null, 2)
          data = new Blob([jsonContent], { type: 'application/json' })
          fileName = `员工绩效数据_${new Date().toISOString().split('T')[0]}.json`
          break

        default:
          message.error('不支持的导出格式')
          return
      }

      // 下载文件
      saveAs(data, fileName)
      message.success(`${format.toUpperCase()}格式导出成功`)
    } catch (error) {
      console.error('导出失败:', error)
      message.error('导出失败')
    }
  }

  // 导出格式选项
  const exportOptions = [
    {
      key: 'excel',
      label: 'Excel格式 (.xlsx)',
      icon: '📊'
    },
    {
      key: 'word',
      label: 'Word格式 (.docx)',
      icon: '📝'
    },
    {
      key: 'pdf',
      label: 'PDF格式 (.pdf)',
      icon: '📄'
    },
    {
      key: 'ppt',
      label: '演示文稿 (.html)',
      icon: '📽️'
    },
    {
      key: 'csv',
      label: 'CSV格式 (.csv)',
      icon: '📋'
    },
    {
      key: 'txt',
      label: '文本格式 (.txt)',
      icon: '📄'
    },
    {
      key: 'json',
      label: 'JSON格式 (.json)',
      icon: '🔧'
    }
  ]

  // 导出下拉菜单项
  const exportMenuItems = exportOptions.map(option => ({
    key: option.key,
    label: (
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <span>{option.icon}</span>
        <span>{option.label}</span>
      </div>
    ),
    onClick: () => handleExport(option.key)
  }))

  // 导入功能，点击按钮时触发隐藏的文件选择框
  const handleImport = () => {
    fileInputRef.current?.click()
  }

  // 下载模板功能，生成并下载一个示例Excel模板
  const handleDownloadTemplate = () => {
    try {
      // 1. 构造模板数据，包含字段和示例内容
      const templateData = [
        {
          '姓名': '张三',
          '部门': '技术部',
          '职位': '前端工程师',
          '角色': '开发人员',
          '手机号': '13800138000',
          '工时成本': '100'
        },
        {
          '姓名': '李四',
          '部门': '产品部',
          '职位': '产品经理',
          '角色': '产品总监',
          '手机号': '13800138001',
          '工时成本': '150'
        }
      ]
      // 2. 转为sheet
      const ws = XLSX.utils.json_to_sheet(templateData)
      // 3. 创建工作簿并添加sheet
      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, '员工绩效模板')
      // 4. 生成Excel文件并下载
      const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
      const data = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
      saveAs(data, '员工绩效导入模板.xlsx')
      message.success('模板下载成功')
    } catch (error) {
      console.error('模板下载失败:', error)
      message.error('模板下载失败')
    }
  }

  // 处理文件上传（导入Excel数据）
  const handleFileUpload = (event) => {
    const file = event.target.files[0]
    if (!file) return

    // 检查文件类型，只允许Excel
    const fileType = file.name.split('.').pop().toLowerCase()
    if (!['xlsx', 'xls'].includes(fileType)) {
      message.error('请上传Excel文件(.xlsx或.xls)')
      return
    }
    // 检查文件大小，限制为5MB
    if (file.size > 5 * 1024 * 1024) {
      message.error('文件大小不能超过5MB')
      return
    }

    const reader = new FileReader()
    reader.onload = async (e) => {
      try {
        // 1. 读取Excel内容并转为json
        const data = new Uint8Array(e.target.result)
        const workbook = XLSX.read(data, { type: 'array' })
        const sheetName = workbook.SheetNames[0]
        const worksheet = workbook.Sheets[sheetName]
        const jsonData = XLSX.utils.sheet_to_json(worksheet)

        // 2. 校验数据是否为空
        if (jsonData.length === 0) {
          message.error('Excel文件中没有数据')
          return
        }
        // 3. 校验字段完整性
        const requiredFields = ['姓名', '部门', '职位', '角色', '工时成本']
        const missingFields = requiredFields.filter(field =>
          !jsonData[0].hasOwnProperty(field)
        )
        if (missingFields.length > 0) {
          message.error(`Excel文件缺少必需字段: ${missingFields.join(', ')}`)
          return
        }
        // 4. 校验每一行数据的必填项
        const invalidRows = []
        jsonData.forEach((row, index) => {
          const missingRequired = requiredFields.filter(field =>
            !row[field] || row[field].toString().trim() === ''
          )
          if (missingRequired.length > 0) {
            invalidRows.push(`第${index + 1}行缺少: ${missingRequired.join(', ')}`)
          }
        })
        if (invalidRows.length > 0) {
          message.error(`数据验证失败:\n${invalidRows.slice(0, 5).join('\n')}${invalidRows.length > 5 ? '\n...' : ''}`)
          return
        }
        // 5. 转换为后端需要的数据格式
        const importData = jsonData.map(row => ({
          name: row['姓名'].toString().trim(),
          department: row['部门'].toString().trim(),
          position: row['职位'].toString().trim(),
          role: row['角色'].toString().trim(),
          phone: row['手机号'] ? row['手机号'].toString().trim() : '',
          workcost: row['工时成本'].toString().trim()
        }))
        // 6. 弹出确认框，确认后批量导入
        Modal.confirm({
          title: '确认导入',
          content: (
            <div>
              <p>确定要导入 {importData.length} 条员工绩效数据吗？</p>
              <p style={{ fontSize: '12px', color: '#666' }}>
                导入后将自动刷新数据列表
              </p>
            </div>
          ),
          onOk: async () => {
            try {
              // 显示加载提示
              message.loading({ content: '正在导入数据...', key: 'import' })
              // 7. 并发请求批量导入
              const promises = importData.map(item =>
                axios.post('http://localhost:3000/EmployeePerformance/add', item)
              )
              await Promise.all(promises)
              // 导入成功提示
              message.success({ content: `成功导入 ${importData.length} 条数据`, key: 'import' })
              getList() // 刷新数据
            } catch (error) {
              console.error('导入失败:', error)
              message.error({ content: '导入失败，请检查数据格式或网络连接', key: 'import' })
            }
          }
        })
      } catch (error) {
        console.error('文件解析失败:', error)
        message.error('文件解析失败，请检查文件格式是否正确')
      }
    }
    // 读取文件内容为ArrayBuffer
    reader.readAsArrayBuffer(file)
    // 清空input值，允许重复上传同一文件
    event.target.value = ''
  }

  // 编辑功能 - 打开编辑模态框并回显数据
  const handleEdit = (record) => {
    // 1. 保存当前要编辑的数据记录
    setCurrentEditData(record)
    // 2. 打开编辑模态框
    setIsEditModalOpen(true)

    // 3. 将当前数据回显到编辑表单中
    editForm.setFieldsValue({
      department: record.department, // 部门
      role: record.role, // 角色
      position: record.position, // 职位
      name: record.name, // 员工姓名
      phone: record.phone, // 手机号
      workcost: record.workcost // 工时成本
    })
  }

  // 编辑模态框保存功能 - 提交更新后的数据
  const handleEditSave = () => {
    // 1. 验证表单数据
    editForm.validateFields().then(values => {
      // 2. 构建更新数据，包含记录ID用于后端定位
      const updateData = {
        ...values, // 表单中的新数据
        _id: currentEditData._id // 记录的唯一标识，用于后端更新指定记录
      }

      // 3. 调用后端更新接口
      axios.post('http://localhost:3000/EmployeePerformance/update', updateData)
        .then(res => {
          if (res.data.code === 200) {
            // 4. 更新成功后的处理
            message.success('更新成功')
            setIsEditModalOpen(false) // 关闭编辑模态框
            editForm.resetFields() // 重置表单数据
            setCurrentEditData(null) // 清空当前编辑数据
            getList() // 刷新数据列表，显示最新数据
          } else {
            // 5. 后端返回错误信息
            message.error(res.data.message || '更新失败')
          }
        })
        .catch(error => {
          // 6. 网络请求失败处理
          console.error('更新失败:', error)
          message.error('更新失败，请检查网络连接')
        })
    })
  }

  // 编辑模态框取消功能 - 关闭模态框并清理数据
  const handleEditCancel = () => {
    setIsEditModalOpen(false) // 关闭编辑模态框
    editForm.resetFields() // 重置表单，清空所有输入内容
    setCurrentEditData(null) // 清空当前编辑数据，释放内存
  }

  return (
    <div style={{ padding: '20px' }}>
      {/* 顶部标题和按钮栏 */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20, border: '1px solid #eee', borderRadius: 4, padding: '10px 16px', background: '#fff' }}>
        <div style={{ fontWeight: 500, fontSize: 16 }}>员工绩效管理</div>
        <div style={{ display: 'flex', gap: 8 }}>
          <Button type="primary" style={{ background: '#F6B657', borderColor: '#F6B657', color: '#fff' }} onClick={() => setIsModalOpen(true)}>添加员工绩效</Button>
          <Button icon={<UploadOutlined />} onClick={handleImport}>导入</Button>
          <Dropdown
            menu={{ items: exportMenuItems }}
            placement="bottomRight"
            trigger={['click']}
          >
            <Button icon={<DownloadOutlined />}>
              导出 <DownOutlined />
            </Button>
          </Dropdown>
          <Button onClick={handleDownloadTemplate}>下载模板</Button>
        </div>
      </div>
      <div style={{ marginBottom: '20px', display: 'flex', gap: '10px' }}>
        <Input.Search
          placeholder="员工姓名"
          style={{ width: 200 }}
          value={searchName}
          onChange={(e) => setSearchName(e.target.value)}
          onSearch={handleSearch}
        />
        <Select
          placeholder="角色选择"
          style={{ width: 200 }}
          value={searchRole}
          onChange={setSearchRole}
          allowClear
          options={roleOptions}
        />
        <Button type="primary" onClick={handleSearch}>查询</Button>
        <Button onClick={handleReset}>重置</Button>
      </div>

      <Table
        rowSelection={rowSelection}
        dataSource={dataSource}
        columns={columns}
        pagination={{
          total: dataSource.length,
          pageSize: pageSize,
          showSizeChanger: true,
          showQuickJumper: true,
          onShowSizeChange: (a, b) => {
            setPageSize(b)
          },
          pageSizeOptions: [2, 3, 5, 10],
          showTotal: (total) => `共 ${total} 条`
        }}
      />

      {/* 底部操作栏 */}
      <div style={{ marginTop: '16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div>
          已选择 {selectedRowKeys.length} 项
        </div>
        <Button
          type="primary"
          danger
          disabled={selectedRowKeys.length === 0}
          onClick={handleDelete}
        >
          删除选中项
        </Button>
      </div>

      {/* 添加员工绩效模态框 */}
      <Modal
        title={<span style={{ fontWeight: 600 }}>添加员工绩效</span>}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        footer={null}
        width={600}
        style={{ top: 40 }}
      >
        <Form
          form={form}
          layout="vertical"
          style={{ marginTop: 16 }}
        >
          <Form.Item label="*所属部门：" name="department" rules={[{ required: true, message: '请选择部门' }]} style={{ marginBottom: 16 }}>
            <Select placeholder="请选择" allowClear options={departmentOptions} />
          </Form.Item>
          <Form.Item label="*所属角色：" name="role" rules={[{ required: true, message: '请选择角色' }]} style={{ marginBottom: 16 }}>
            <Select placeholder="请选择" allowClear options={roleOptions} />
          </Form.Item>
          <Form.Item label="*所属职位：" name="position" rules={[{ required: true, message: '请选择职位' }]} style={{ marginBottom: 16 }}>
            <Select placeholder="请选择" allowClear options={positionOptions} />
          </Form.Item>
          <Form.Item label="*选择员工：" name="name" rules={[{ required: true, message: '请选择员工' }]} style={{ marginBottom: 16 }}>
            <Select placeholder="请选择" allowClear options={employeeOptions} />
          </Form.Item>
          <Form.Item label="手机号：" name="phone" style={{marginBottom:16}}>
            <Input placeholder="请输入手机号" />
          </Form.Item>
          <Form.Item label="*工时成本：" name="workcost" rules={[{required:true,message:'请输入工时成本'}]} style={{marginBottom:16}}>
            <Input placeholder="请输入" addonAfter="元/小时" />
          </Form.Item>
          <div style={{ textAlign: 'center', marginTop: 24 }}>
            <Button type="primary" htmlType="submit" style={{ marginRight: 16 }} onClick={handleOk}>保存</Button>
            <Button onClick={handleCancel}>取消</Button>
          </div>
        </Form>
      </Modal>

      {/* 编辑员工绩效模态框 */}
      <Modal
        title={<span style={{ fontWeight: 600 }}>编辑员工绩效</span>}
        open={isEditModalOpen}
        onOk={handleEditSave}
        onCancel={handleEditCancel}
        footer={null}
        width={600}
        style={{ top: 40 }}
      >
        <Form
          form={editForm}
          layout="vertical"
          style={{ marginTop: 16 }}
        >
          <Form.Item label="*所属部门：" name="department" rules={[{ required: true, message: '请选择部门' }]} style={{ marginBottom: 16 }}>
            <Select placeholder="请选择" allowClear options={departmentOptions} />
          </Form.Item>
          <Form.Item label="*所属角色：" name="role" rules={[{ required: true, message: '请选择角色' }]} style={{ marginBottom: 16 }}>
            <Select placeholder="请选择" allowClear options={roleOptions} />
          </Form.Item>
          <Form.Item label="*所属职位：" name="position" rules={[{ required: true, message: '请选择职位' }]} style={{ marginBottom: 16 }}>
            <Select placeholder="请选择" allowClear options={positionOptions} />
          </Form.Item>
          <Form.Item label="*选择员工：" name="name" rules={[{ required: true, message: '请选择员工' }]} style={{ marginBottom: 16 }}>
            <Select placeholder="请选择" allowClear options={employeeOptions} />
          </Form.Item>
          <Form.Item label="手机号：" name="phone" style={{marginBottom:16}}>
            <Input placeholder="请输入手机号" />
          </Form.Item>
          <Form.Item label="*工时成本：" name="workcost" rules={[{required:true,message:'请输入工时成本'}]} style={{marginBottom:16}}>
            <Input placeholder="请输入" addonAfter="元/小时" />
          </Form.Item>
          <div style={{ textAlign: 'center', marginTop: 24 }}>
            <Button type="primary" htmlType="submit" style={{ marginRight: 16 }} onClick={handleEditSave}>保存</Button>
            <Button onClick={handleEditCancel}>取消</Button>
          </div>
        </Form>
      </Modal>

      {/* 隐藏的文件输入框 */}
      <input
        ref={fileInputRef}
        type="file"
        accept=".xlsx,.xls"
        style={{ display: 'none' }}
        onChange={handleFileUpload}
      />
    </div>
  )
}
